import React, { useContext, useState, useCallback } from 'react';

import { Alert, Upload, message, Button, UploadProps, Spin } from 'antd';

import { UploadContext } from '../useUploadModal';

import cls from 'classnames';

import '../index.less';
import { IFirstStepUpload } from '../type';

import MyIcon from '@/components/MyIcon';

import { UploadOutlined, DownloadOutlined } from '@ant-design/icons';
import { downloadTemplate, getTenant } from '@/utils';

export const FirstStepUpload: React.FC<IFirstStepUpload> = ({ prefix, alert, template, upload }) => {
  const contentPrefix = prefix + '-content';

  const [downLoading, setDownLoading] = useState(false);
  const [upLoading, setUpLoading] = useState(false);

  const { current, dispatch } = useContext(UploadContext);

  const onSetUploadInfo = (info: any) => {
    if (info) {
      dispatch({
        type: 'setUploadInfo',
        payload: {
          uploadInfo: info,
        },
      });

      if (info?.dataList) {
        updateDataList(info?.dataList);
      }
    }
  };

  const updateDataList = (list: Record<string, any>[]) => {
    if (list && list?.length > 0) {
      dispatch({
        type: 'updateDataList',
        payload: {
          dataList: list,
        },
      });
    }
  };

  const onSetCurrent = useCallback(
    (current: any) => {
      dispatch({
        type: 'changeCurrent',
        payload: {
          current: current,
        },
      });
    },
    [current],
  );

  const onResetUpload = () => {
    dispatch({
      type: 'setUploadInfo',
      payload: {
        uploadInfo: null,
      },
    });
  };

  /* 上传 */
  const uploadProps: UploadProps = {
    accept: '.xls,.xlsx',
    headers: {
      tenantName: getTenant(),
    },
    onChange(info) {
      if (info.file.status == 'uploading') {
        setUpLoading(true);
      }
      if (info.file.status === 'done') {
        if (info.file?.response) {
          if (info.file?.response?.success) {
            message.success(`${info.file.name} 上传成功`);
            if (info.file?.response?.obj) {
              onSetUploadInfo(info.file?.response?.obj);
            }
            onSetCurrent(1);
            setUpLoading(false);
          } else {
            // message.error('发现错误信息');
            if (info.file?.response?.obj) {
              onSetUploadInfo(info.file?.response?.obj);
            }
            onSetCurrent(1);
            setUpLoading(false);
          }
        }
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 上传失败`);
        onResetUpload();
        setUpLoading(false);
      }
    },
    onRemove: (file) => {
      if (file) {
        onResetUpload();
      }
    },
    ...upload?.uploadProps,
  };

  const downLoadCall = () => {
    setDownLoading(false);
  };

  return (
    <div className={cls(contentPrefix + '-body')} style={{ display: current === 0 ? 'block' : 'none' }}>
      <Spin spinning={upLoading}>
        {template?.showTemplate && (
          <div className={prefix + '-card'}>
            <div className={cls(prefix + '-card-icon')}>
              <MyIcon type={'icon-download1'} />
            </div>
            <div className={cls(prefix + '-card-info')}>
              <div className={cls(prefix + '-card-info-title')}>{template?.title ?? ''}</div>
              <div className={cls(prefix + '-card-info-describe')}>{template?.description ?? ''}</div>
              <div className={cls(prefix + '-card-info-download')}>
                <Button
                  icon={<DownloadOutlined />}
                  type={'link'}
                  size={'small'}
                  loading={downLoading}
                  onClick={() => {
                    setDownLoading(true);
                    const url = template?.templateUrl;
                    const title = template?.templateFileName;
                    const filePath = template?.templateFilePath;
                    downloadTemplate(url, title, filePath, downLoadCall);
                  }}
                >
                  下载模板
                </Button>
              </div>
            </div>
          </div>
        )}
        <div className={cls(prefix + '-card')}>
          <div className={cls(prefix + '-card-icon')}>
            <MyIcon type={'icon-upload1'} />
          </div>
          <div className={cls(prefix + '-card-info')}>
            <div className={cls(prefix + '-card-info-title')}>{upload?.title ?? ''}</div>
            <div className={cls(prefix + '-card-info-describe')}>{upload?.description ?? ''}</div>
            <div className={cls(prefix + '-card-info-download')}>
              <Upload {...uploadProps} className={'download'}>
                <Button icon={<UploadOutlined />} type={'link'} size={'small'}>
                  上传文件
                </Button>
              </Upload>
            </div>
          </div>
        </div>
        {alert && alert?.showAlert && (
          <Alert message={alert?.message ?? ''} description={alert?.description ?? ''} type={alert?.type ?? 'warning'} showIcon />
        )}
      </Spin>
    </div>
  );
};
